import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class GoodsController extends GetxController {
  final nameController = TextEditingController();
  final priceController = TextEditingController();
  final descriptionController = TextEditingController();

  final selectedCampus = ''.obs;
  final campusSelected = false.obs;
  final selectedTag = ''.obs;
  final selectedImages = <XFile>[].obs;

  // 默认图片URL
  final String defaultImageUrl =
      'https://twt-trade-platform.oss-cn-beijing.aliyuncs.com/242fac3d-0fe2-4b66-9b04-94f339550433.jpg';

  // 获取显示图片列表（本地路径或默认URL）
  List<String> get displayImages {
    if (selectedImages.isEmpty) {
      return [defaultImageUrl];
    } else {
      return selectedImages.map((file) => file.path).toList();
    }
  }

  void selectTag(String tag) {
    selectedTag.value = selectedTag.value == tag ? '' : tag;
  }

  void clearForm() {
    nameController.clear();
    priceController.clear();
    descriptionController.clear();
    selectedCampus.value = '';
    campusSelected.value = false;
    selectedTag.value = '';
    selectedImages.clear();
  }

  Future<void> pickImage() async {
    Get.dialog(const Center(child: CircularProgressIndicator()));
    try {
      if (selectedImages.length >= 9) {
        Get.snackbar('提示', '最多只能选择9张图片');
        return;
      }

      final picker = ImagePicker();
      final pickedFiles = await picker.pickMultiImage(
        maxWidth: 1000,
        maxHeight: 1000,
        imageQuality: 80,
      );

      final remainingSlots = 9 - selectedImages.length;
      final filesToAdd = pickedFiles.take(remainingSlots).toList();

      if (filesToAdd.isNotEmpty) {
        selectedImages.addAll(filesToAdd);
      }

      if (pickedFiles.length > remainingSlots) {
        Get.snackbar('提示', '已自动选择前$remainingSlots张图片');
      }
    } finally {
      Get.back();
    }
  }

  void removeImage(int index) {
    if (index >= 0 && index < selectedImages.length) {
      selectedImages.removeAt(index);
      selectedImages.refresh();
    }
  }
}